<?php

require_once ROOT_DIR.'models/Message.php';
require_once ROOT_DIR.'views/MessageJSON.php';
require_once ROOT_DIR.'controls/RightHelper.php';

/**
 * Retrieves all Messages and responses linked with the given list, todo, msg or user
 * 
 * @param int $listID
 * @param int $todoID
 * @param int $msgID
 * @param int $userID
 * @param boolean $fullResponse
 */
function getMsgs($listID, $todoID, $msgID, $userID, $authorID = null, $fullResponse = false, $from = 0, $rows = 30, $order = 'asc'){
	if(is_null($fullResponse)) $fullResponse = false;
	
	if(is_null($listID)) $listID = '';
	if(is_null($todoID)) $todoID = '';
	if(is_null($msgID)) $msgID = '';
	if(is_null($userID)) $userID = '';
	
	if(is_null($from)) $from = 0;
	if(is_null($rows)) $rows = 30;
	if(is_null($order)) $order = 'asc';
	
	if($_SESSION['USER_NAME'] == 'admin' 
			|| $userID != ''
			|| ($listID != '' && RightHelper::sharesList((int)$listID))
			|| ($todoID != '' && RightHelper::checkIfLinkedToTodo((int)$todoID))
			|| (!is_null($authorID) && $authorID == $_SESSION['USER_ID'])
			|| ($msgID != '' && RightHelper::checkIfThreadVisible((int)$msgID))
	){
		if($userID != '' && $userID != $_SESSION['USER_ID']) $authorID = $_SESSION['USER_ID'];
		$msg = Message::getMessages($msgID, $todoID, $listID, $userID, $authorID, $from, $rows, $order);
		$count = Message::getMessageCount($msgID, $todoID, $listID, $userID, $authorID);
		echo MessageJSON::getView($msg, $fullResponse, $count, $order);
	} else {
		$res = new ResultJSON(true, session_id(), ERROR_NOT_ALLOWED);
		echo $res->renderView();
	}
}

?>